package com.zf.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 全局过滤器：给所有经过网关的请求添加 TRACE_ID 请求头
 **/
@Component
public class AddTraceIdHeaderGlobalFilter implements GlobalFilter, Ordered {
    public static final String TRACE_ID = "TRACE_ID";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 如果已经存在了 TRACE_ID 请求头，则不做任何处理
        if (exchange.getRequest().getHeaders().containsKey(TRACE_ID)) {
            return chain.filter(exchange);
        }

        // 给所有经过网关的请求加上一个全局 TRACE_ID 请求头
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(TRACE_ID, UUID.randomUUID().toString())
                .build();
        // 重新封装请求
        ServerWebExchange newExchange = exchange.mutate().request(request).build();
        // 传递给下一级
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
